<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="材质ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入材质id"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材质编码" prop="matCode">
        <el-input
          v-model="queryParams.matCode"
          placeholder="请输入材质编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="材质名称" prop="matName">
        <el-input
          v-model="queryParams.matName"
          placeholder="请输入材质名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" ref="toolbar">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          @click="handleAdd"
          v-hasPermi="['business:matMgmt:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:matMgmt:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:matMgmt:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          @click="handleExport"
          v-hasPermi="['business:matMgmt:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div ref="divTable" :style="'height:' + divHeight + 'px'">
      <el-table v-loading="loading" :data="matMgmtList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="center" width="50">
          <template v-slot="scope">
            {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="材质编码" align="center" prop="matCode" />
        <el-table-column label="材质名称" align="center" prop="matName" />
        <el-table-column label="状态" align="center" prop="matStatus" width="55">
          <template v-slot="scope">
            <dict-tag :options="dict.type.sys_status" :value="scope.row.matStatus"/>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['business:matMgmt:edit']"
            >修改</el-button>
            <el-button
              type="text"
              :icon="scope.row.matStatus === 'DELETED' ? 'el-icon-refresh-left' : 'el-icon-delete'"
              @click="handleChangeStatus(scope.row)"
              v-hasPermi="['business:storeMgmt:changeStatus']"
            >{{scope.row.matStatus === 'DELETED' ? "恢复" : "删除" }}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-show="total>0"
          :pageRefs="this.$refs"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
      />
    </div>
    <!-- 添加或修改材质管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="材质编码" prop="matCode">
          <el-input v-model="form.matCode" placeholder="请输入材质编码" />
        </el-form-item>
        <el-form-item label="材质名称" prop="matName">
          <el-input v-model="form.matName" placeholder="请输入材质名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" clearable type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMatMgmt, getMatMgmt, addMatMgmt, updateMatMgmt, exportExcel, updateChangeStatus, getDoesItExist, delMatMgmt } from "@/api/business/matMgmt";
import ResizeMixin from "@/layout/mixin/ResizeHandler";

export default {
  name: "MatMgmt",
  mixins: [ResizeMixin],
  dicts: ['sys_status'],
  data() {
    const validateReferenceLink = (rule, value, callback) => {
      this.checkReferenceLink(rule.field, value).then(res => {
        if (!res.isUnique) {
          callback(new Error(res.msg));
        } else {
          callback();
        }
      });
    };
    return {
      // div高度
      divHeight: 0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 材质管理表格数据
      matMgmtList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        matCode: null,
        matName: null,
        matStatus: null,
        userId: null,
        deptId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        matCode: [
          { required: true, message: '请输入材质编码', trigger: 'blur' },
          { validator: validateReferenceLink, trigger: 'blur' }
        ],
        matName: [
          { required: true, message: '请输入材质名称', trigger: 'blur' },
          { validator: validateReferenceLink, trigger: 'blur' }
        ],
      },
      userIdList: [],
      deptIdList: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    checkReferenceLink(field, value) {
      let obj = {};
      obj[field] = value;
      obj.id = this.form.id;
      return new Promise(resolve => {
        if (value){
          getDoesItExist(obj).then(response => {
            resolve({isUnique: response.data.length  == 0, msg: field == 'matCode'?'材质编码不能重复':'材质名称不能重复' });
          });
        }else {
          resolve(true);
        }
      });
    },
    /** 查询材质管理列表 */
    getList() {
      this.loading = true;
      listMatMgmt(this.queryParams).then(response => {
        this.matMgmtList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        matCode: null,
        matName: null,
        matStatus: null,
        userId: null,
        deptId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.$resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.$resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加材质管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getMatMgmt(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改材质管理";
      });
    },
    /** 解锁或锁定按钮操作 */
    handleChangeStatus(row) {
      const ids = row.id || this.ids;
      let status = row.matStatus === 'NORMAL'? '删除' : '恢复';
      this.$modal.confirm('是否确认' + status + '此数据项？').then(function() {
        row.matStatus = row.matStatus === 'NORMAL'? 'DELETED' : 'NORMAL';
        return updateChangeStatus({ ids: ids, status: row.matStatus })
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(status + "成功");
      }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMatMgmt(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMatMgmt(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('注意：此删除不可恢复，是否确认删除？').then(function() {
        return delMatMgmt(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      exportExcel(this.queryParams)
    }
  }
};
</script>
